import { instantiate, Node, Prefab, resources } from "cc";
import EntityBase from "./EntityBase";

/**
 * 实体管理器
 * 游戏内的物体称之为实体
 * 实体可能重复创造多次，所以这个管理器只保存实体的预制件
 */
export default class EntityManager{
    
    public static readonly  Entity_PREFABS_PATH : string = "prefabs/Entity/";

    public static get Instance() : EntityManager {
        if(!this._Instance)
            this._Instance = new EntityManager();
        return this._Instance; 
    }
    private static _Instance : EntityManager;

    private constructor(){
        
    }

    private prefabs : Map<string,Prefab> = new Map();

    public async GetEntity<T extends EntityBase>(key:string) : Promise<T>{
        //  从map获取prefab
        var prefab = this.prefabs.get(key);
        //  如果没有，尝试加载
        if(!prefab){
            prefab = await this.loadPrefab(key);
        }
        let node = instantiate(prefab);

        let entity = node.getComponent(EntityBase);
        if(!entity){
            entity = node.addComponent(EntityBase);
        }
        return entity as T;
        
    }

    private loadPrefab(key:string) : Promise<Prefab>{
        var path = EntityManager.Entity_PREFABS_PATH + key;
        return new Promise<Prefab>(
            (resolve, reject)=>{
                resources.load(path,Prefab,
                    (err,prefab)=>{
                        if(err)
                        {
                            reject("EntityManager: Failed Load UI "+key);
                        }
                        resolve(prefab);
                });
            }
        );
    }    
    
    public Init(){
        
    }
}